<?php
namespace Backend\Controllers\Setting\Sys;

use Backend\Controllers\BaseController;
use Backend\Models\Sys\Menu;
use Backend\Models\Sys\Role;

class RoleController extends BaseController
{
    public static $outTree = [];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 获取系统用户角色
     *
     * /sys/role/gets/invalid/
     * /sys/role/gets/valid/
     */
    public function getsAction()
    {
        $result = (new Role())->gets();
        if ($result === false) {
            return $this->json([
                'code' => 500,
                'msg'  => '获取失败，系统错误~'
            ]);
        }
        foreach ($result as $index => $item) {
            $html  = '';
            $menus = json_decode($item['view'], true);
            foreach ($menus as $topMenu) {
                $isNext = false;
                $html   .= '<span title="' . $topMenu['url'] . '">' . $topMenu['name'] . '</span>';
                if (isset($topMenu['submenus']) && count($topMenu['submenus']) > 0) {
                    foreach ($topMenu['submenus'] as $upMenu) {
                        if (!$isNext) {
                            $html   .= '<br/>　└';
                            $isNext = true;
                        }
                        $html .= '&nbsp;&nbsp;<span title="' . $upMenu['url'] . '">' . $upMenu['name'] . '</span>';
                        if (isset($upMenu['submenus']) && count($upMenu['submenus']) > 0) {
                            $isNext = false;
                            foreach ($upMenu['submenus'] as $menu) {
                                if (!$isNext) {
                                    $html   .= '<br/>　　　└';
                                    $isNext = true;
                                }
                                $html .= '&nbsp;&nbsp;<span title="' . $menu['url'] . '">' . $menu['name'] . '</span>';
                            }
                        }
                    }
                }
                $html .= '<br/>';
            }
            $result[$index]['view'] = $html;
        }
        return $this->json([
            'code'  => 200,
            'roles' => $result
        ]);
    }

    public function getAction()
    {
        $id = $this->request->getPost('id');
        if (empty($id)) {
            return $this->json([
                'code' => 301,
                'msg'  => '获取角色失败，系统错误~'
            ]);
        }
        $role   = new Role();
        $entity = $role->get($id);
        if ($entity === false) {
            return $this->json([
                'code' => 302,
                'msg'  => '获取角色失败，系统错误~'
            ]);
        }
        $menus = json_decode($entity['view'], true);
        $menu  = [];
        foreach ($menus as $index => $item) {
            if (isset($item['submenus']) && count($item['submenus']) > 0) {
                foreach ($item['submenus'] as $child) {
                    if (isset($child['submenus']) && count($child['submenus']) > 0) {
                        foreach ($child['submenus'] as $value) {
                            $menu[] = $value['name'];
                        }
                    }
                    $menu[] = $child['name'];
                }
            }
            $menu[] = $item['name'];
        }
        unset($entity['view']);
        return $this->json([
            'code'  => 200,
            'role'  => $entity,
            'roles' => $menu
        ]);
    }

    public function updateAction()
    {
        $data   = [
            'role'  => $this->request->getPost('role'),
            'menus' => $this->request->getPost('menus'),
        ];
        $entity = [
            'id'     => $data['role']['id'],
            'name'   => $data['role']['name'],
            'status' => $data['role']['status'],
            'view'   => $data['menus']
        ];
        if ($entity['id'] == '' || !is_numeric($entity['id'])) {
            return $this->json([
                'code' => 500,
                'msg'  => '角色丢失，系统错误~'
            ]);
        }
        if ($entity['name'] == '') {
            return $this->json([
                'code' => 302,
                'msg'  => '角色名不能为空~'
            ]);
        }
        if ($entity['status'] == -1) {
            return $this->json([
                'code' => 303,
                'msg'  => '请选择角色状态~'
            ]);
        }
        if ($entity['view'] == '') {
            return $this->json([
                'code' => 303,
                'msg'  => '权限序列化列表不能为空~'
            ]);
        }
        $menus = json_decode($data['menus'], true);
        foreach ($menus as $key => $value) {
            if (isset($value['submenus']) && count($value['submenus']) > 0) {
                foreach ($value['submenus'] as $idx => $child) {
                    if (isset($child['submenus']) && count($child['submenus']) > 0) {
                        $value['submenus'][$idx]['submenus'] = array_values($child['submenus']);
                    }
                    if ($child['submenus'] == '') {
                        unset($value['submenus'][$idx]);
                    }
                }
                $menus[$key]['submenus'] = array_values($value['submenus']);
            }
        }
        $entity['view'] = json_encode(array_values($menus), JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);
        $role           = new Role();
        $result         = $role->edit($entity);
        if ($result !== false) {
            return $this->json([
                'code' => 200,
                'msg'  => '编辑角色成功~'
            ]);
        } else {
            return $this->json([
                'code' => 201,
                'msg'  => '编辑角色失败，系统错误~'
            ]);
        }
    }

    public function addAction()
    {
        $data   = [
            'role'  => $this->request->getPost('role'),
            'menus' => $this->request->getPost('menus'),
        ];
        $entity = [
            'name'   => $data['role']['name'],
            'status' => $data['role']['status'],
            'view'   => $data['menus']
        ];
        if ($entity['name'] == '') {
            return $this->json([
                'code' => 302,
                'msg'  => '角色名不能为空~'
            ]);
        }
        if ($entity['status'] == -1) {
            return $this->json([
                'code' => 303,
                'msg'  => '请选择角色状态~'
            ]);
        }
        if ($entity['view'] == '') {
            return $this->json([
                'code' => 303,
                'msg'  => '权限序列化列表不能为空~'
            ]);
        }
        $role  = new Role();
        $check = $role->isExists($entity['name']);
        if ($check === -500) {
            return $this->json([
                'code' => 202,
                'msg'  => '新增角色失败，系统错误~'
            ]);
        }
        if ($check) {
            return $this->json([
                'code' => 203,
                'msg'  => '已经存在相同的角色名称~'
            ]);
        }
        $menus = json_decode($data['menus'], true);
        foreach ($menus as $key => $value) {
            if (isset($value['submenus']) && count($value['submenus']) > 0) {
                foreach ($value['submenus'] as $idx => $child) {
                    if (isset($child['submenus']) && count($child['submenus']) > 0) {
                        $value['submenus'][$idx]['submenus'] = array_values($child['submenus']);
                    }
                    if ($child['submenus'] == '') {
                        unset($value['submenus'][$idx]);
                    }
                }
                $menus[$key]['submenus'] = array_values($value['submenus']);
            }
        }
        $entity['view'] = json_encode(array_values($menus), JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);
        $result         = $role->add($entity);
        if ($result !== false) {
            return $this->json([
                'code' => 200,
                'msg'  => '新增角色成功~'
            ]);
        } else {
            return $this->json([
                'code' => 201,
                'msg'  => '新增角色失败，系统错误~'
            ]);
        }
    }

    public function getMenusAction()
    {
        $menu  = new Menu();
        $menus = $menu->getRoleMenus();
        if ($menus === false || !is_array($menus)) {
            return $this->json([
                'code' => 301,
                'msg'  => '获取菜单失败，系统错误~'
            ]);
        }
        $out = [];
        foreach ($menus as $index => $item) {
            if ($item['level'] == 1) {
                $out[$item['id']] = [
                    'id'       => $item['id'],
                    'name'     => $item['name'],
                    'url'      => $item['url'],
                    'icon'     => $item['icon'],
                    'top'      => $item['top'],
                    'up_id'    => $item['up_id'],
                    'submenus' => [],
                ];
            } elseif ($item['level'] == 2) {
                $out[$item['up_id']]['submenus'][$item['id']] = [
                    'id'       => $item['id'],
                    'name'     => $item['name'],
                    'url'      => $item['url'],
                    'icon'     => $item['icon'],
                    'top'      => $item['top'],
                    'up_id'    => $item['up_id'],
                    'submenus' => []
                ];
            } else {
                $out[$item['top']]['submenus'][$item['up_id']]['submenus'][$item['id']] = [
                    'id'    => $item['id'],
                    'name'  => $item['name'],
                    'url'   => $item['url'],
                    'icon'  => $item['icon'],
                    'top'   => $item['top'],
                    'up_id' => $item['up_id'],
                ];
            }
        }
        foreach ($out as $key => $value) {
            if (isset($value['submenus']) && count($value['submenus']) > 0) {
                foreach ($value['submenus'] as $idx => $child) {
                    if (isset($child['submenus']) && count($child['submenus']) > 0) {
                        $value['submenus'][$idx]['submenus'] = array_values($child['submenus']);
                    }
                }
                $out[$key]['submenus'] = array_values($value['submenus']);
            }
        }
        return $this->json([
            'code'  => 200,
            'menus' => array_values($out)
        ]);
    }
}
